﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;
using ClassLibrary;

using System.Threading;
using SharpSvn;
using Timer=System.Threading.Timer;

namespace Test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        #region IP

        private void btnSetIPInternet_Click(object sender, EventArgs e)
        {
            IPProvider.SetIPAddress("192.168.123." + tbIPInternet.Text.Trim(), "255.255.255.0", "192.168.123.254");
            string[] strings = new string[2];
            strings[0] = "219.150.32.132";
            strings[1] = "219.146.30.130";
            IPProvider.SetDNS(strings);
        }

        private void btnSetNetworkAdapter_Click(object sender, EventArgs e)
        {
            IPProvider.SetNetworkAdapter(rbSetNetworkAdapter.Checked);
        }

        private void btnIPSpecialNet_Click(object sender, EventArgs e)
        {
            IPProvider.SetIPAddress("10.222.1." + tbIPSpecialNet.Text.Trim(), "255.255.255.0", "10.222.1.69");
            string[] strings = new string[2];
            IPProvider.SetDNS(strings);
        }

        #endregion

        #region 加解密

        private void btnEncrypt_Click(object sender, EventArgs e)
        {
            Encrypt_Decrypt ed = new Encrypt_Decrypt(Application.StartupPath + "\\Choose.bin");
            ed.Serialize("dddddddd");
        }

        private void btnDecrypt_Click(object sender, EventArgs e)
        {
            Encrypt_Decrypt ed = new Encrypt_Decrypt(Application.StartupPath + "\\Choose.bin");
            string s = (string)ed.DeSerialize();
            MessageBox.Show(s);
        }

        #endregion

        #region 计算

        //计算
        private void btnCalculate_Click(object sender, EventArgs e)
        {
            int sum = 0;

            for (int i = Convert.ToInt32(tbStart.Text); i <= Convert.ToInt32(tbEnd.Text); i++)
            {
                sum += i;
            }

            sum *= Convert.ToInt32(tbCount.Text);

            lbResult.Text = sum.ToString();
        }

        #endregion

        #region 异常

        //产生异常
        private void btnException_Click(object sender, EventArgs e)
        {
            ////主程序异常
            //int j = 5 - 5;
            //int i = 8 / j;

            ////timer1.Enabled = true;

            Timer timer=new Timer(ddd,null,1,1);
        }

        private void ddd(object state)
        {
            int j = 5 - 5;
            int i = 8 / j;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            int j = 5 - 5;
            int i = 8 / j;
        }

        #endregion

        #region Xml

        string xml = Application.StartupPath + "\\XmlFile.xml";

        private void btnXmlAdd_Click(object sender, EventArgs e)
        {
            //插入元素
            XmlHelper.Insert(xml, "/Root", "Studio", "", "");
            //插入元素/属性
            XmlHelper.Insert(xml, "/Root/Studio", "Site", "Name", "小路工作室");
            XmlHelper.Insert(xml, "/Root/Studio", "Site", "Name", "丁香鱼工作室");
            XmlHelper.Insert(xml, "/Root/Studio", "Site", "Name", "谱天城工作室");
            XmlHelper.Insert(xml, "/Root/Studio/Site[@Name='谱天城工作室']", "Master", "", "红尘静思");
            //插入属性
            XmlHelper.Insert(xml, "/Root/Studio/Site[@Name='小路工作室']", "", "Url", "http://www.wzlu.com/");
            XmlHelper.Insert(xml, "/Root/Studio/Site[@Name='丁香鱼工作室']", "", "Url", "http://www.luckfish.net/");
            XmlHelper.Insert(xml, "/Root/Studio/Site[@Name='谱天城工作室']", "", "Url", "http://www.putiancheng.com/");
        }

        private void btnXmlUpdate_Click(object sender, EventArgs e)
        {
            //修改元素值
            XmlHelper.Update(xml, "/Root/Studio/Site[@Name='谱天城工作室']/Master", "", "RedDust");
            //修改属性值
            XmlHelper.Update(xml, "/Root/Studio/Site[@Name='谱天城工作室']", "Url", "http://www.putiancheng.net/");
            XmlHelper.Update(xml, "/Root/Studio/Site[@Name='谱天城工作室']", "Name", "PuTianCheng Studio");
        }

        private void btnXmlDelete_Click(object sender, EventArgs e)
        {
            //删除属性
            XmlHelper.Delete(xml, "/Root/Studio/Site[@Name='小路工作室']", "Url");
            //删除元素
            XmlHelper.Delete(xml, "/Root/Studio", "");
        }

        private void btnXmlRead_Click(object sender, EventArgs e)
        {
            string s = "";
            //读取元素值
            //s = XmlHelper.Read(xml, "/Root/Studio/Site/Master", "");
            //读取属性值
            //s = XmlHelper.Read(xml, "/Root/Studio/Site", "Url");
            //读取特定属性值
            s = XmlHelper.Read(xml, "/Root/Studio/Site[@Name='丁香鱼工作室']", "Url");

            MessageBox.Show(s);
        }

        #endregion

        #region 随机数

        //生成随机数
        private void btnGetRandom_Click(object sender, EventArgs e)
        {
            int[] a=new int[100];
            a=GetRandomArray(5, 1, 5);

            string strI = "";
            foreach (int i in a)
            {
                strI += i;
            }

            MessageBox.Show(strI);
        }

        /// <summary>
        /// 功能描述：返回不重复随机数数组
        /// 作者：    杨艳峰
        /// 创建日期：2006-4-30
        /// </summary>
        /// <param name="Num">随机数个数</param>
        /// <param name="minNum">随机数下限</param>
        /// <param name="maxNum">随机数上限</param>
        /// <returns></returns>
        public int[] GetRandomArray(int Number, int minNum, int maxNum)
        {
            int j;
            int[] b = new int[Number];
            Random r = new Random(unchecked((int)DateTime.Now.Ticks));
            for (j = 0; j < Number; j++)
            {
                int i = r.Next(minNum, maxNum + 1);
                int num = 0;
                for (int k = 0; k < j; k++)
                {
                    if (b[k] == i)
                    {
                        num = num + 1;
                    }
                }
                if (num == 0)
                {
                    b[j] = i;
                }
                else
                {
                    j = j - 1;
                }
            }
            return b;
        }

        #endregion

        #region svn测试

        //svn测试
        //SharpSvn主页：http://sharpsvn.open.collab.net/
        private void btnSvnTest_Click(object sender, EventArgs e)
        {
            using (SvnClient client = new SvnClient())
            {
                SvnInfoEventArgs serverInfo;
                SvnInfoEventArgs clientInfo;
                SvnUriTarget repos = new SvnUriTarget("https://smartwebdev.googlecode.com/svn/trunk");
                SvnPathTarget local = new SvnPathTarget(@"E:\smart");

                client.GetInfo(repos, out serverInfo);
                client.GetInfo(local, out clientInfo);

                string path = @"E:\smart";
                client.CleanUp(path);
                client.Revert(path);
                client.Update(path);

                Console.WriteLine(string.Format("serverInfo revision of {0} is {1}", repos, serverInfo.Revision));
                Console.WriteLine(string.Format("clientInfo revision of {0} is {1}", local, clientInfo.Revision));
            }
        }

        private List<string> tooltips = new List<string>();
        Queue<SvnLogEventArgs> logItems = new Queue<SvnLogEventArgs>();
        readonly object instanceLock = new object();
        private delegate void LogRetriever();
        delegate void PopulateHandler();

        private void retrieveButton_Click(object sender, EventArgs e)
        {
            clearButton.Enabled = false;
            retrieveButton.Enabled = false;

            LogRetriever retriever = new LogRetriever(retrieveAndRenderLog);


            retriever.BeginInvoke(new AsyncCallback(LogDone), null);
        }

        /// <summary>
        /// Retrieves the Subversion log entries and potentially updates the
        /// DataGridView in a streaming fashion.
        /// </summary>
        private void retrieveAndRenderLog()
        {
            string targetPath = pathTextBox.Text;
            SvnTarget target;

            if (string.IsNullOrEmpty(targetPath) ||
                !SvnTarget.TryParse(targetPath, out target))
            {
                MessageBox.Show(this, "The path you've specified is not valid.  " +
                    "Please provide a valid URL or filesystem path pointing to " +
                    "a Subversion resource.",
                    "Invalid Path", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                logGridView.Rows.Clear();

                // SvnClient is disposable, using makes sure it's disposed every time
                using (SvnClient client = new SvnClient())
                {
                    SharpSvn.UI.SharpSvnUI.Bind(client, this);

                    try
                    {
                        client.Log(target.FileName,
                        delegate(object lSender, SvnLogEventArgs le)
                        {
                            le.Detach(); // detach from client
                            lock (instanceLock) // Queue isn't thread-safe, let's lock
                            {
                                logItems.Enqueue(le);
                            }

                            // Optionally add items in a streaming way on the other thread
                            InvokePopulateGrid();

                            StringBuilder tooltip = new StringBuilder();

                            tooltip.AppendLine("Changed Paths:");

                            foreach (SvnChangeItem path in le.ChangedPaths)
                            {
                                tooltip.AppendLine("");
                                tooltip.Append(path.Action + " " + path.Path);

                                if (path.CopyFromRevision != -1)
                                    tooltip.Append(" (" + path.CopyFromPath +
                                        "[" + path.CopyFromRevision + "])");
                            }

                            tooltips.Add(tooltip.ToString());
                        });
                    }
                    catch (Exception exc)
                    {
                        MessageBox.Show(this, exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }


        /// <summary>
        /// Decides whether to populate the DataGridView on the current thread
        /// or by invoking another thread.
        /// </summary>
        void InvokePopulateGrid()
        {
            if (InvokeRequired) // this is not the UI thread, and needs invoking
                Invoke(new PopulateHandler(PopulateProcessGrid));
            else // this is the UI thread, call directly
                PopulateProcessGrid();
        }

        /// <summary>
        /// Populates the DataGridView with the Subversion log entries.
        /// </summary>
        void PopulateProcessGrid()
        {
            lock (instanceLock) // Queue isn't thread-safe, let's lock
            {
                while (logItems.Count > 0)
                {
                    SvnLogEventArgs le = logItems.Dequeue();
                    string[] row = new string[4];

                    row[0] = le.Revision.ToString();
                    row[1] = le.Time.ToLocalTime().ToShortDateString();
                    row[2] = le.Author.ToString();
                    row[3] = le.LogMessage.ToString();

                    logGridView.Rows.Add(row);
                }
            }

            toggleButtons();
        }

        /// <summary>
        /// Toggles the "Clear" and "Retrieve" buttons based on the
        /// contents of the Path text box.
        /// </summary>
        public void toggleButtons()
        {
            /// Handle the clear button
            if (pathTextBox.Text.Length > 0)
            {
                clearButton.Enabled = true;
            }
            else
            {
                clearButton.Enabled = false;
            }

            /// Handle the retrieve button
            if (clearButton.Enabled)
            {
                retrieveButton.Enabled = true;
            }
            else
            {
                retrieveButton.Enabled = false;
            }
        }

        /// <summary>
        /// Asynchronous callback.
        /// </summary>
        void LogDone(IAsyncResult rslt)
        {
            InvokePopulateGrid();
        }

        private void clearButton_Click(object sender, EventArgs e)
        {

        }

        //svn例子move
        private void btnSvnMove_Click(object sender, EventArgs e)
        {
            using (SvnClient client = new SvnClient())
            {
                // Checkout the code to the specified directory
                client.CheckOut(new Uri("https://testcccccc.googlecode.com/svn/trunk/"),
                                        "c:\\testcccccc");

                // Update the specified working copy path to the head revision
                client.Update("c:\\testcccccc");
                SvnUpdateResult result;
                client.Update("c:\\testcccccc", out result);


                //client.Move("c:\\sharpsvn\\from.txt", "c:\\sharpsvn\\new.txt");

                //client.Delete("c:\\testcccccc\\新建文本文档.txt");

                // Commit the changes with the specified logmessage
                SvnCommitArgs ca = new SvnCommitArgs();
                ca.LogMessage = "Moved from.txt to new.txt";


                NetworkCredential networkCredential = new NetworkCredential("15081895597@139.com", "Ym3ER7Wq2Bj5");
                networkCredential.Domain = "1";

                client.Authentication.DefaultCredentials = networkCredential;


                //SomeFictitiousCredentialsClass credentials = client.Authentication.DefaultCredentials.FictitiousGetCachedCredentialsMethod();
                //client.Authentication.DefaultCredentials.GetCredential(
                //    new Uri("https://classlibrary.googlecode.com/svn/trunk"), "1");
                // Call my code that performs svnmucc-like work here, passing username and password
                // obtained from 'credentials' variable.

                client.Commit("c:\\testcccccc", ca);
            }
        }

        private void pathTextBox_TextChanged(object sender, EventArgs e)
        {
            toggleButtons();
        }

        #endregion
    }
}
